import React from "react";
// import Todo from "./templates/Todo.rt";
// import Kb from "./templates/kb.rt";
//  import bd from "./templates/bd.rt";
//  import df from "./templates/df.rt";
import {currentUser } from "@/services/auth";
import {Button, Divider, Select,Layout} from "antd/lib";
import {convertStringToComponent} from "@/components/contract/utils";
import notification from "@/services/notification";
import Templates from "@/services/templates";
import EditorDemo from "@/components/contract/new/EditorDemo";
import Editor from "@/components/contract/new/Editor";
import FileViewer from 'react-file-viewer'; 
import { axios } from "@/services/axios";
import { inject, observer } from 'mobx-react';
//const timer_str = convertComponentToString(df)
const {Sider,Content } = Layout;
// 将转化的组件字符串再转为组件
// const TimerComponent = convertStringToComponent(this.props.templatecontent)

class Template extends React.Component {
    state = {
      loading: true,
      tdata:[
        {
          id: 0,
          code: "word",
          name: "WORD模板",
         },
      {
       id: 1,
       code: "空白模板",
       name: "空白模板",
      },
    ],
  };
  componentWillMount() {
      this.fetch();
  }
  fetch = () => {
    let param={
      page: 1,
      pagesize: 20,
      code: "",
      name: "",
      type: "",
      orgunit_id: this.props.contractStore.contractModel.departmentid,
    }
     Templates.getlist(param).then(data => {
        this.setState({
            loading: false,
            tdata:data.data,
        });
    });
  };
    componentDidUpdate() {
      if(this.props.contractStore.contractModel.templateid >1) {
        document.getElementById("goods_detail_content").innerHTML = this.props.contractStore.contractModel.templatecontent;
      }

    }
  //  componentWillUnmount() {
  //   let timer_str;
  //   if(this.state.templateid ===1) {
  //     timer_str = this.childedit.state.contracteditor.toHTML()
  //   }else if(this.state.templateid ===0) {
  //     timer_str=this.state.templatecontent;
  //   }else{
  //     timer_str = document.getElementById("goods_detail_content").innerHTML
  //   }
  //   const data=
  //     {
  //       templateid: this.state.templateid,
  //       checkmessage: this.state.checkmessage,
  //       templatecontent: timer_str,
  //       xiuzhengupload:this.state.xiuzhengupload,
  //     }
  //   　　this.props.childchange2(data);
  // }

handleupload= () => {
    var filedom = document.querySelector('#templatefile');
    filedom.click();  
    this.props.contractStore.contractModel.setXiuzhengupload(true);    
};
  handlesubmit = () => {
    if(this.props.contractStore.contractModel.templateid ===1){
      const htmlContent = this.childedit.state.contracteditor.toHTML();
      this.props.contractStore.contractModel.setTemplatecontent(htmlContent);
      notification.success("提交成功.");
    }else if(this.props.contractStore.contractModel.templateid ===0) {
      // 触发选择文件模拟点击事件
      // const filedom = document.getElementById('templatefile');
      // filedom.click()
      var filedom = document.querySelector('#templatefile');
      filedom.click();
    }else{
      let obj = document.getElementsByClassName("contracttemplate");
      let list = Array.from(obj)
      list.forEach((item)=>{
          if(item.localName==="textarea"){
             document.getElementById(item.id).setAttribute('innerHTML',item.value);
          }else{
             document.getElementById(item.id).setAttribute('value',item.value);
          }
      });
      let timer_str = document.getElementById("goods_detail_content").innerHTML;
      this.props.contractStore.contractModel.setTemplatecontent(timer_str);
      notification.success("提交成功.");
    }
     
  };
  handledown= () => {
    let  filename=this.props.contractStore.contractModel.templatecontent;
    if(filename ===''){
      return;
    }
    //let nums=filename.lastIndexOf("/");
    let name=filename.substr(filename.lastIndexOf("/")+1);
    let AjaxUrl = 'api/upload/downloadfile';
    fetch(AjaxUrl ,{
     method: 'POST',
     body: window.JSON.stringify({filename: filename}),
     credentials: 'include',
     headers: new Headers({
       'Content-Type': 'application/json'
     })}).then((response) => {
     response.blob().then(blob => {
       const aLink = document.createElement('a');
       document.body.appendChild(aLink);
       aLink.style.display='none';
       const objectUrl = window.URL.createObjectURL(blob);
       aLink.href = objectUrl;
       aLink.download = name;
       aLink.click();
       document.body.removeChild(aLink);
     });
   }).catch((error) => {
     console.log(error);
   });
  };

   templateChange = value => {
     let temps="";
      this.state.tdata.some(function(item){
      if(item.id===value) {
        temps = item.template;
        return true;
      }
      });
      this.props.contractStore.contractModel.setTemplateid(value);
      this.props.contractStore.contractModel.setTemplatecontent(temps);
  };
  renderTemplateSelect(){
    return (
      <Select style={{ width: 400 }}
       value={this.props.contractStore.contractModel.templateid}
       onChange={(value) => this.templateChange(value)}
       disabled ={!this.props.contractStore.contractModel.isedit}
      >
        {(this.state.tdata || []).map(item => (
          <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
        ))}
      </Select>
    );
  };
  fileChange= (event) => {
    const formData = new FormData();
    let files=event.target.files[0];
    formData.append('file', files);
    let app = this;
    axios.post('api/upload/uploadcontracttextfile/'+this.props.contractStore.contractModel.id, formData).then(res => {
      res.url = 'static/file/'+res.filename;
      res.name=files.name;
      console.log(res);
      app.props.contractStore.contractModel.setTemplatecontent(res.url);
      notification.success("提交成功.");
    }).catch(error => {
    });
    event.target.value="";
  }
    render() {
      let templatecontent =this.props.contractStore.contractModel.templatecontent;
      if(this.props.contractStore.contractModel.templateid ===0 && templatecontent !==''){
        templatecontent=templatecontent.replace('.docx','.pdf');
        templatecontent=templatecontent.replace('.doc','.pdf');
        templatecontent=templatecontent +"?noCache=" +Math.random()+"/"
      }
      return (
        <div >
          <div style={{ marginBottom: 16 }}>
            <span style={{ marginLeft: 8 }}>
              模版：
            </span>
            {this.renderTemplateSelect()}
            <Divider type="vertical" />
            <Button type="primary" onClick={() => this.handlesubmit()}
            disabled ={!this.props.contractStore.contractModel.isedit}>
              <i className="fa fa-save m-r-5" />
              {this.props.contractStore.contractModel.templateid ===0 ? "文件上传":"合同正文保存"}
            </Button>
            {(this.props.contractStore.contractModel.templateid ===0) && (<Divider type="vertical" />)}
            {(this.props.contractStore.contractModel.templateid ===0) && (<Button type="primary" onClick={() => this.handledown()}>
              <i className="fa fa-save m-r-5" />
              下载编辑
            </Button>
            )}
            {(this.props.contractStore.contractModel.templateid ===0) && (<Divider type="vertical" />)}
            {(this.props.contractStore.contractModel.status ===2 && this.props.contractStore.contractModel.templateid ===0 && currentUser.hasPermission("editcontractcode")) && (<Divider type="vertical" />)}
            {(this.props.contractStore.contractModel.status ===2 && this.props.contractStore.contractModel.templateid ===0 && currentUser.hasPermission("editcontractcode")) && (<Button type="primary" onClick={() => this.handleupload()}
            >
              <i className="fa fa-save m-r-5" />
              修正格式上传(pdf)
            </Button>
            )}
          </div>
         {(this.props.contractStore.contractModel.templateid ===1) && ( <EditorDemo  templatecontent ={templatecontent}
         onRef={(ref) => { this.childedit = ref; }} 
          disabled ={!this.props.contractStore.contractModel.isedit}/>
        )} 
        <input id="templatefile" type="file" 
        style={{ display: "none"}}
        accept=".doc,.docx,.pdf" onChange={this.fileChange} multiple/>
        {(this.props.contractStore.contractModel.templateid ===0) && (templatecontent !=='') && ( 
        <iframe src={templatecontent} width='100%' height='800px' frameborder='1'>
                </iframe>
        )}
        {(this.props.contractStore.contractModel.templateid ===0) && (templatecontent ==='') && ( <label >请点击【文件上传】导入WORD文档</label>
        )}
      {(this.props.contractStore.contractModel.templateid >1) && ( <div id="goods_detail_content" disabled ={!this.props.contractStore.contractModel.isedit}/>
        )}
    </div>
      );
    }
}
export default inject('contractStore')(observer(Template));